/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
 *
 */

import path from 'path';

import fse from 'fs-extra';

import { OhosLogger } from '../utils/log/ohos-logger.js';
import { ProcessUtils } from '../utils/process-utils.js';
import { TaskNames } from './common/task-names.js';
import { TargetTaskService } from './service/target-task-service.js';
import { getHqfName } from './sign/sign-util.js';
import { OhosHapTask } from './task/ohos-hap-task.js';

export class PackageHqf extends OhosHapTask {
  private _log: OhosLogger = OhosLogger.getLogger(PackageHqf.name);

  constructor(targetService: TargetTaskService) {
    super(targetService, TaskNames.Task.PACKAGE_HQF);
  }

  protected async doTaskAction(): Promise<void> {
    const command = this.getPatchConfigMode() !== 'hotReload' ? this.getColdReloadCommand() : this.getHotReloadCommand();
    await new ProcessUtils().execute(command, { encoding: 'utf-8' });
  }

  getHotReloadCommand() {
    const hqfPackage = path.resolve(this.pathInfo.getModuleBuildOutputPath(), getHqfName(this.moduleName, this.targetName, false));
    const packageTool: string = this.sdkInfo.getPackageTool();
    const patchJson: string = path.resolve(this.pathInfo.getModuleBuildIntermediates(), 'hotReload', 'patch.json');

    const buildConfig = fse.readJsonSync(this.pathInfo.getBuildConfigPath());
    const etsPath = buildConfig.patchConfig.patchAbcPath;

    const command: string[] = ['java', '-jar', packageTool, '--mode', 'hqf'];
    command.push('--json-path', patchJson);
    command.push('--ets-path', etsPath);
    command.push('--out-path', hqfPackage);
    command.push('--force', 'true');

    return command;
  }

  getColdReloadCommand() {
    const patchResfilePath = path.resolve(this.pathInfo.getPatchDir(), 'resources');
    const patchLibsDir = path.resolve(this.pathInfo.getPatchDir(), 'libs');
    const hqfPackage = path.resolve(this.pathInfo.getModuleBuildOutputPath(), getHqfName(this.moduleName, this.targetName, false));
    const resourcePath = path.resolve(patchResfilePath);

    const packageTool: string = this.sdkInfo.getPackageTool();
    const patchJson: string = path.resolve(this.pathInfo.getPatchDir(), 'patch.json');

    const command: string[] = ['java', '-jar', packageTool, '--mode', 'hqf'];
    command.push('--json-path', patchJson);
    command.push('--lib-path', patchLibsDir);
    command.push('--ets-path', path.resolve(this.pathInfo.getPatchDir(), 'ets'));
    command.push('--resources-path', resourcePath);
    command.push('--out-path', hqfPackage);
    command.push('--force', 'true');

    return command;
  }

  /**
   * 用于根据buildConfig文件里的mode判断重载类型
   * 值：hotReload coldReload
   */
  getPatchConfigMode() {
    const buildConfigPath = this.pathInfo.getBuildConfigPath();
    if (fse.existsSync(buildConfigPath)) {
      const buildConfig = fse.readJsonSync(buildConfigPath);
      return buildConfig?.patchConfig?.mode;
    } else {
      this._log.error(`${buildConfigPath} is not exists`);
    }
  }

  initTaskDepends(): void {
    this.declareDepends(TaskNames.Task.PREPARE_QUICKFIX.name);
  }
}
